//microcommand define gzrand
var db = require("@lnnbot-private/gzmtr.json")

function distCoord(R, coord1, coord2) {
 var jing1 = coord1[0] / R;
 var wei1 = 2 * Math.atan(Math.exp(coord1[1] / R)) - Math.PI / 2;
 var jing2 = coord2[0] / R;
 var wei2 = 2 * Math.atan(Math.exp(coord2[1] / R)) - Math.PI / 2;
 var djing = jing2 - jing1;
 var dwei = wei2 - wei1;
 return 2 * R * Math.asin(Math.sqrt( Math.pow(Math.sin(dwei/2), 2) + Math.cos(wei1) * Math.cos(wei2) * Math.pow(Math.sin(djing/2), 2) ));
}
function dist(R, coord, place1, place2) {
 return distCoord(R, coord[place1], coord[place2]);
}

signature("[站名:string] [范围:number]", "随机输出广州地铁站名")
usage("指定站名时，随机输出距离该站点一定范围内的站点名。范围单位为千米，默认为5。")
option("count", "-n <数量:integer> 在符合条件的站名中随机选择指定数量的来输出，缺省值为1。")
option("inclusive", "-i 包括有轨（默认不考虑有轨和城际）。")
option("all", "-a 不随机选择，只输出所有符合条件的站名。")
action(({ session, options }, ...params) => {
    var station_set = new Set();
    for (const line of db.lines) 
     if ((!!options.inclusive || line["num"].charAt(0) !== "T") && line["num"].charAt(0) !== "C") {
      for (const st of line["stations"])
       station_set.add(st);
     }
    
    var station_universe = new Set()
    if (params.length === 0) {
     for (const st of station_set)
      station_universe.add(st);
    }
    else {
     const R = 6378137;
     var origin = params[0];
     if (!station_set.has(origin))
      return "地铁站不存在...";
     maxDist = 5;
     if (params.length > 1)
      maxDist = Number(params[1]);
     maxDist = maxDist * 1000;
     for (const st of station_set)
      if (dist(R, db.coord, origin, st) <= maxDist)
       station_universe.add(st);
    }
    
    if (!!options.all) {
     let bj = 0;
     var outstr = "";
     for (const st of station_universe) {
      if (bj == 1)
       outstr = outstr + " ";
      outstr = outstr + st;
      bj = 1;
     }
     return outstr;
    }
    else {
     var permut = Array.from(station_universe);
     var count = 1;
     if (typeof options.count === "number")
      count = options.count;
     if (count > permut.length)
      count = permut.length;
     var ind = Array.from( { length : permut.length }, ( _, index ) => index )
     var outstr = "";
     for ( let i = 0; i < count; i++ ) {
      let j = Math.floor( Math.random() * (permut.length - i) ) + i;
      let tmp = ind[i];
      ind[i] = ind[j];
      ind[j] = tmp;
      if (i > 0) outstr = outstr + " ";
      outstr = outstr + permut[ind[i]];
     }
     return outstr
    }
  })